package xcmg.device.service.threeParty;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xcmg.device.feign.BaiduTransClient;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.vo.threeParty.BaiduTranslateResultDO;
import xcmg.device.util.MD5Utils;
import yb.ecp.fast.infra.infra.ActionResult;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BaiduApiService {

    @Value("${baidu.trans.appid}")
    private String appid;

    @Value("${baidu.trans.securityKey}")
    private String securityKey;
    @Autowired
    private BaiduTransClient baiduTransClient;

    /**
     * @Des 百度翻译api
     * @Date 2021/3/30 9:35
     * @Author wangzhaoyu
     * @Param [originMaterialsDesc]
     * @Return yb.ecp.fast.infra.infra.ActionResult<java.lang.String>
     */
    public BaiduTranslateResultDO materialsDescTranslate(String originMaterialsDesc){
        BaiduTranslateResultDO result = new BaiduTranslateResultDO();
        if(StringUtils.isEmpty(originMaterialsDesc)){
            return result;
        }
        try{
            //随机数
            String salt = String.valueOf(System.currentTimeMillis());
            // 签名
            String src = appid + originMaterialsDesc + salt + securityKey; // 加密前的原文
            String sign = MD5Utils.md5(src);
            Map transMap = baiduTransClient.getMaterialsTrans(originMaterialsDesc,"auto","en", appid, salt, sign);
            //转化为对象
            if(transMap.get("error_code") == null){
                String materialsDescEn = (String) ((Map) ((List) transMap.get("trans_result")).get(0)).get("dst");
                return result.successResult(materialsDescEn);
            }else{
                log.info("查询百度翻译失败：" + transMap.get("error_msg"));
                return result.errorResult(ErrorCode.MaterialsTransError);
            }
        }catch (Exception e){
            log.error("查询百度翻译异常：{}",e);
            return result.errorResult(ErrorCode.MaterialsTransError);
        }
    }
}
